package com.yzyz.data;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yzyz.bean.route.RouteBean;
import com.yzyz.bean.route.RouteGroupBean;

/**
 * 包含线路分组以及线路分组下面的所有线路
 * @author David Sun
 * @Date   2010-4-7
 *
 */
public class RouteGroupStore {
	Log logger = LogFactory.getLog(RouteGroupStore.class);
	private HashMap<Integer, RouteGroupBean> cachedRoutes = new HashMap<Integer, RouteGroupBean>();
	/**
	 * 初始化
	 * @param routes
	 */
	public synchronized  void init(List<RouteGroupBean> routes){
		if(this.cachedRoutes != null){
			this.cachedRoutes.clear();
		}
		for(RouteGroupBean route: routes){
			this.cachedRoutes.put(route.getId(), route);
		}
	}
	
	/**
	 * 通过行程编号以及组编号从缓存中获取行程
	 * @param routeId
	 * @param routeGroupId
	 * @return
	 */
	public synchronized  RouteBean getRouteByRouteIdAndGroupId(int routeId, int routeGroupId){
		RouteGroupBean routeGroup = cachedRoutes.get(routeGroupId);
		if(routeGroup == null){
			return null;
		}
		List<RouteBean> routes = routeGroup.getRoutes();
		if(routes==null || routes.size() == 0){
			return null;
		}
		for(RouteBean route: routes){
			if(route.getId() == routeId){
				return route;
			}
		}
		return null;
	}
	
	/**
	 * 通过组名来查询组
	 * @param name
	 * @return
	 */
	public synchronized  RouteGroupBean searchByName(String name){
		Set<Entry<Integer, RouteGroupBean>> entrys = cachedRoutes.entrySet();
		for(Entry<Integer, RouteGroupBean> entry: entrys){
			RouteGroupBean group = entry.getValue();
			if(group.getName().trim().equals(name.trim())){
				return group;
			}
		}
		
		return null;
	}
	
	/**
	 * 通过routeId来获取route
	 * @param routeId
	 * @return
	 */
	public synchronized RouteBean getRoute(int routeId){
		Set<Entry<Integer, RouteGroupBean>> entrys = cachedRoutes.entrySet();
		for(Entry<Integer, RouteGroupBean> entry: entrys){
			RouteGroupBean group = entry.getValue();
			for(RouteBean route: group.getRoutes()){
				if(route.getId() == routeId){
					return route;
				}
			}
		}
		return null;
	}
	
	public synchronized RouteGroupBean getRouteGroup(int routeGroupId){
		return this.cachedRoutes.get(routeGroupId);
	}
	
	
}
